package org.grayrabbit.cms.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 *    HanYuPinYinUtil.java
 *    @author   hasau 
 *    2011-8-30    下午1:47:47  
 */
public class HanYuPinYinUtil {
	public static String hanZiToPinYin(String src){           
		char[] chars = null;
		chars = src.toCharArray();
		String[] tmp = new String[chars.length];
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);
		format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
		String pinYin = "";
		int index = chars.length;
		try {
			for (int i = 0; i < index; i++) {
				// 判断是否为汉字字符
				if (java.lang.Character.toString(chars[i]).matches(
						"[\\u4E00-\\u9FA5]+")) {
					tmp = PinyinHelper.toHanyuPinyinStringArray(chars[i], format);
					pinYin += tmp[0];
				} else
					pinYin += java.lang.Character.toString(chars[i]);
			}
			return pinYin;
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return pinYin;
    } 
}
